package com.sinovate.liteEMS.web.shiro.filter;

import com.sinovate.liteEMS.Constants;
import com.sinovate.liteEMS.session.dao.MySqlSessionDAO;

import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ForceLogoutFilter extends AccessControlFilter {

	@Autowired
	private MySqlSessionDAO sessionDAO;

	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		Session session = getSubject(request, response).getSession(false);
		if (session == null) {
			return true;
		}
		return session.getAttribute(Constants.SESSION_FORCE_LOGOUT_KEY) == null;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);
		sessionDAO.delete(subject.getSession(false));
		try {
			subject.logout();// 强制退出
		} catch (Exception e) {
			/* ignore exception */e.printStackTrace();
		}

		String loginUrl = getLoginUrl()
				+ (getLoginUrl().contains("?") ? "&" : "?") + "forceLogout=1";
		WebUtils.issueRedirect(request, response, loginUrl);
		return false;
	}

}